package api

import (
	"encoding/json"
	"ims/app/dao"
	"ims/app/model"
	"ims/app/ws"
	"ims/tools/response"
	"time"

	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gorilla/websocket"
)

// @Summary 发送消息接口
// @Produce  json
// @Accept multipart/form-data
// @Param from_id formData   string true "来源uid"
// @Param to_id formData   string true "目标uid"
// @Param content formData   string true "内容"
// @Param type formData   string true "类型|kefu,visitor"
// @Success 200 {object} controller.Response
// @Failure 200 {object} controller.Response
// @Router /message [post]
func SendMessage(r *ghttp.Request) {
	fromId := r.GetFormString("from_id")
	toId := r.GetFormString("to_id")
	content := r.GetFormString("content")
	cType := r.GetFormString("type")
	if content == "" {
		response.JsonResponse(r, g.Map{
			"code": 400,
			"msg":  "内容不能为空",
		})
		return
	}

	var kefuInfo model.User
	var vistorInfo model.Visitor
	if cType == "kefu" {
		kefuInfo = dao.FindUser(fromId)
		vistorInfo = dao.FindVisitorByVistorId(toId)
	} else if cType == "visitor" {
		vistorInfo = dao.FindVisitorByVistorId(fromId)
		kefuInfo = dao.FindUser(toId)
	}

	if kefuInfo.Id == 0 || vistorInfo.Id == 0 {
		response.JsonResponse(r, g.Map{
			"code": 400,
			"msg":  "用户不存在",
		})
		return
	}
	dao.CreateMessage(kefuInfo.Name, vistorInfo.VisitorId, content, cType)

	if cType == "kefu" {
		guest, ok := clientList[vistorInfo.VisitorId]
		if guest == nil || !ok {
			response.JsonResponse(r, g.Map{
				"code": 200,
				"msg":  "ok",
			})
			return
		}
		conn := guest.conn

		msg := TypeMessage{
			Type: "message",
			Data: ClientMessage{
				Name:    kefuInfo.Nickname,
				Avator:  kefuInfo.Avator,
				Id:      kefuInfo.Name,
				Time:    time.Now().Format("2006-01-02 15:04:05"),
				ToId:    vistorInfo.VisitorId,
				Content: content,
			},
		}
		str, _ := json.Marshal(msg)
		PushServerTcp(str)
		conn.WriteMessage(websocket.TextMessage, str)
	}
	if cType == "visitor" {
		kefuConns, ok := kefuList[kefuInfo.Name]
		if kefuConns == nil || !ok {
			response.JsonResponse(r, g.Map{
				"code": 200,
				"msg":  "ok",
			})
			return
		}
		msg := TypeMessage{
			Type: "message",
			Data: ClientMessage{
				Avator:  vistorInfo.Avator,
				Id:      vistorInfo.VisitorId,
				Name:    vistorInfo.Name,
				ToId:    kefuInfo.Name,
				Content: content,
				Time:    time.Now().Format("Y-m-d H:i:s"),
			},
		}
		str, _ := json.Marshal(msg)
		PushServerTcp(str)
		for _, kefuConn := range kefuConns {
			kefuConn.WriteMessage(websocket.TextMessage, str)
		}
	}
	response.JsonResponse(r, g.Map{
		"code": 200,
		"msg":  "ok",
	})
}

//关闭一个对话
func SendCloseMessageV2(r *ghttp.Request) {
	visitorId := r.GetQueryString("visitor_id")
	if visitorId == "" {
		response.JsonResponse(r, g.Map{
			"code": 400,
			"msg":  "visitor_id不能为空",
		})
		return
	}
	msg := TypeMessage{
		Type: "close",
		Data: visitorId,
	}
	str, _ := json.Marshal(msg)
	for _, visitor := range ws.ClientList {
		if visitorId == visitor.Id {
			if err := visitor.Conn.WriteMessage(websocket.TextMessage, str); err != nil {
				visitor.Conn.Close()
				delete(ws.ClientList, visitorId)
			}
		}
	}
	response.JsonResponse(r, g.Map{
		"code": 200,
		"msg":  "ok",
	})
}
